(ns future-app.ios.core
  (:require [reagent.core :as r :refer [atom]]
            [re-frame.core :refer [subscribe dispatch dispatch-sync]]
            [future-app.ios.style :refer [calc-style]]
            [future-app.ios.calc :as calc]
            [future-app.events]
            [future-app.subs]))

(def ReactNative (js/require "react-native"))

(def app-registry (.-AppRegistry ReactNative))
(def text (r/adapt-react-class (.-Text ReactNative)))
(def text-input (r/adapt-react-class (.-TextInput ReactNative)))
(def view (r/adapt-react-class (.-View ReactNative)))
(def image (r/adapt-react-class (.-Image ReactNative)))
(def touchable-highlight (r/adapt-react-class (.-TouchableHighlight ReactNative)))

(def logo-img (js/require "./images/cljs.png"))

(def input-buttons [["C" "+/-" "%" "/"]
                    [1, 2, 3, "*"],
                    [4, 5, 6, "-"],
                    [7, 8, 9, "+"],
                    [0, ".", "="]])

(defn input-button [label]
  [touchable-highlight {:style [(assoc (:input-button calc-style)
                                       :flex (if (= 0 label) 2 1))
                                (when (calc/highlight? label)
                                  (:input-button-highlighted calc-style))]
                        :underlay-color "#193441"
                        :on-press #(calc/calc-handler label)}
   [text {:style (:input-button-text calc-style)}
    label]])

(defn app-root []
  [view {:style (:root-container calc-style)}
   [view {:style (:display-container calc-style)}
    [text {:style (:display-text calc-style)}
     (calc/display-text)]]
   [view {:style (:input-container calc-style)}
    (map-indexed (fn [i row] 
                   ^{:key (str "row-" i)}
                   [view {:style (:input-row calc-style)}
                    (map-indexed (fn [j e]
                                   ^{:key (str i "-" j)}
                                   [input-button e])
                                 row)])
                 input-buttons)]])

;; (defn app-root []
;;   (let [greeting (subscribe [:get-greeting])]
;;     (fn []
;;       [view {:style {:flex-direction "column" :margin 40 :align-items "center" :background-color "white"}}
;;        [text {:style {:font-size 30 :font-weight "100" :margin-bottom 20 :text-align "center"}} @greeting]
;;        [image {:source logo-img
;;                :style  {:width 80 :height 80 :margin-bottom 30}}]
;;        [text-input {:placeholder "username2..." :style {:height 50 :width "100%"}
;;                     :on-change-text (fn [text] (dispatch [:set-greeting text]))}]       
;;        [touchable-highlight {:style {:background-color "#999" :padding 10 :border-radius 5}
;;                              :on-press #(alert "HELLO!")}
;;         [text {:style {:color "white" :text-align "center" :font-weight "bold"}} "press me"]]])))

(defn init []
      (dispatch-sync [:initialize-db])
      (.registerComponent app-registry "FutureApp" #(r/reactify-component app-root)))
